<template>
  <div style="padding-top: 24px;">
    <a-table
      ref="table"
      size="middle"
      :scroll="{x:true}"
      rowKey="key"
      bordered
      :columns="defColumns"
      :dataSource="dataSource"
      :pagination="false"
      :loading="loading"
      class="j-table-force-nowrap"
      @change="handleTableChange">
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
      <!-- <a-divider type="vertical"/> -->
      <!-- <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
        <a-button
          class="ruleButton"
          :ghost="true"
          type="primary"
          :hidden="disabled"
          icon="delete"
          :disabled="isDisabledAuth('paybackDisclaimerDisclaimerInfo:delete')"/>
      </a-popconfirm> -->
      </span>
    </a-table>
    <ErpOmcContractTaxRateInfoModal
    ref="modalForm"
    :contractId="contractId"
    :projectId="projectId"
    :managementTeam="managementTeam"
    :undertaker="undertaker"
    @dataOne="dataOne"
    @ok="modalFormOk"></ErpOmcContractTaxRateInfoModal>
  </div>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ErpOmcContractTaxRateInfoModal from './ErpOmcContractTaxRateInfoModal'
  import { getAction,postAction } from '@/api/manage'
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import Vue from 'vue';
  import { filterObj } from '@/utils/util'
import indexVue from '../../../../../../components/gis/navTitle/index.vue'
  export default {
    name: 'ErpOmcContractTaxRateInfoList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpOmcContractTaxRateInfoModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      contractId: {
        type: String,
        default: '',
        required: false
      },
      managementTeam: {
        type: String,
        default: '',
        required: false
      },
      undertaker: {
        type: String,
        default: '',
        required: false
      },
      projectId: {
        type: String,
        default: '',
        required: false
      },
    },
    data () {
      return {
        params: {
          mianId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: '',
          order: ''
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        description: '收款合同-合同税率信息列表',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '含税金额(元)',
            align: "center",
            dataIndex: 'amount'
          },
          {
            title:'税率(%)',
            align:"center",
            dataIndex: 'taxRate_dictText'
          },
          {
            title:'税额(元)',
            align:"center",
            dataIndex: 'taxation'
          },
          {
            title:'未税金额(元)',
            align:"center",
            dataIndex: 'untaxedAmount'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:160,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: "/api/erp/omc/contractmanager/erpOmcContractRate/list",
          delete: "/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/delete",
          deleteBatch: "/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/deleteBatch",
          exportXlsUrl: "/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/exportXls",
          importExcelUrl: "/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/importExcel",
        },
        dictOptions:{},
        superFieldList:[],
        showAdd: false,
        visibleDetail: false,
        disableMixinCreated: true
      }
    },
    created() {
      this.getSuperFieldList();
      this.initColumns()
      if(this.disabled){
        this.defColumns.pop()
      }
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'BigDecimal',value:'amountReceivable',text:'应收金额',dictCode:''})
        fieldList.push({type:'string',value:'exemptionType',text:'豁免类型（1：经营团队，2：项目承接人，3：项目负责人）',dictCode:''})
        fieldList.push({type:'string',value:'exemptionManagementTeam',text:'豁免经营团队',dictCode:''})
        fieldList.push({type:'string',value:'exemptionUndertaker',text:'豁免项目承接人',dictCode:''})
        fieldList.push({type:'string',value:'exemptionProjectHead',text:'豁免项目负责人',dictCode:''})
        this.superFieldList = fieldList
      },



      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id, type) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        var url = ''
        if (type && type == '2') {
          url = '/api/erp/omc/contractmanager/erpOmcContractRateFinal/list'
        } else {
          url = '/api/erp/omc/contractmanager/erpOmcContractRate/list'
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.contractId = id
        }
        this.loading = true
        getAction(url, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            // 当type为2时，代表为变更，则需要把id重新赋值给finalId
            if (type && type == '2') {
              if (this.dataSource && this.dataSource.length > 0) {
                this.dataSource.forEach((item, index) => {
                  item.finalId = item.id
                  item.key = index
                })
              }
            } else {
              this.dataSource.forEach((item, index) => {
                item.key = index
              })
            }
            // 判断是否当前页没有数据且为第一页
            if (this.dataSource.length == 0 && this.ipagination.current == 1) {
              initDictOptions('contract_rate_type').then((res) => {
                if (res.success) {
                  this.$set(this.dictOptions, 'contractRateType', res.result)
                  this.dataSource = this.dictOptions.contractRateType.map((item, index) => {
                    return {
                      key: index,
                      amount: 0, // 含税金额
                      taxRate: item.value, // 税率
                      taxRate_dictText: item.text, // 税率
                      taxation: 0, // 税额
                      untaxedAmount: 0, // 未税金额
                    } 
                  })
                } else {
                  this.$message.error(res.message)
                }
              })
            }
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },

      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          this.showAdd = false
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
      },

      handleEdit: function (record) {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
      },

      handleAdd: function () {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      },

      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },

      modalFormOk() {
        // 新增/修改 成功时，重载列表
        // this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },

      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },

      dataOne(data, flag) {
        if (flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key, 1, data);
        }
        if(this.dataSource.length == 1) {
          this.showAdd = true
        }
      },

      submitForm() {
        return this.dataSource
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
